package parkingManage.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import parkingManage.dao.ParkingDao;
import parkingManage.model.ParkingModel;
import parkingManage.utils.DBUtils;

public class ParkingDaoImpl implements ParkingDao {

	@Override
	public List<ParkingModel> selectAll() {
		List<ParkingModel> list = new ArrayList<ParkingModel>();

		// 获取连接
		Connection conn = DBUtils.getConnection();
		Statement sta = null;
		ResultSet result = null;

		ParkingModel park;
		try {
			// 获取状态集
			sta = conn.createStatement();
			// 获取结果集
			result = sta.executeQuery("select * from parking_lot");

			while (result.next()) {
				int lotCode = result.getInt("lot_id");
				int status = result.getInt("status");
				park = new ParkingModel(lotCode, status);
				list.add(park);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtils.closeAll(sta, conn, result);
		}
		return list;
	}

	@Override
	public ParkingModel selectByLot(int lotCode) {
		// 获取连接
		Connection conn = DBUtils.getConnection();
		PreparedStatement ps = null;
		ResultSet result = null;
		ParkingModel parkingModel = null;

		String sql = "select * from parking_lot where lot_id=?";
		try {
			// 执行SQL语句
			ps = conn.prepareStatement(sql);
			ps.setInt(1, lotCode);

			result = ps.executeQuery();
			while (result.next()) {
				int status = result.getInt("status");

				parkingModel = new ParkingModel(lotCode, status);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtils.closeAll(ps, conn, result);
		}
		return parkingModel;
	}

	@Override
	public int park(int lotCode) {
		Connection conn = DBUtils.getConnection();
		PreparedStatement ps = null;
		String sql = "update parking_lot set status = 1 where lot_id = ?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, lotCode);

			int k = ps.executeUpdate();
			return k;

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtils.closeAll(ps, conn, null);
		}
		return 0;
	}

	@Override
	public int pickup(int lotCode) {
		Connection conn = DBUtils.getConnection();
		PreparedStatement ps = null;
		String sql = "update parking_lot set status = 0 where lot_id = ?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, lotCode);

			int k = ps.executeUpdate();
			return k;

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtils.closeAll(ps, conn, null);
		}
		return 0;
	}

}
